
#include <QFileDialog>
#include <QFileInfo>
#include <QFontDialog>

#include <Qsci/qscilexer.h>

#include <string>

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_currentDirectory = QApplication::applicationDirPath();

    ui->textEdit->setMarginLineNumbers(1, true);
    ui->textEdit->setFolding(QsciScintilla::PlainFoldStyle, 2);

    ui->textEdit->setBraceMatching(QsciScintilla::SloppyBraceMatch);
    ui->textEdit->setAutoIndent(true);
    ui->textEdit->setIndentationGuides(true);

    m_textChanged = false;

    connect(ui->textEdit, SIGNAL(textChanged()), this, SLOT(textChanged()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_actionOpen_triggered()
{
    QString filename = QFileDialog::getOpenFileName(this, tr("Open File"), ".", tr("*"));
    QsciLexer* lexer = m_lang.getLexer(filename);

    ui->textEdit->setLexer(lexer);

    if(!QFile::exists(filename)) return ;
    QString fileText = m_helper.loadFileText(filename);
    ui->textEdit->setText(fileText);

    int lineCount = ui->textEdit->lines();
    int lineCountOrderOfMagnitude = 1;

    for(int countStart=lineCount; countStart > 1; )
    {
        lineCountOrderOfMagnitude++;
        countStart /= 10;
    }

    ui->textEdit->setMarginWidth(1, 10 * lineCountOrderOfMagnitude);
}

void MainWindow::on_actionSave_triggered()
{
    m_helper.saveFileText(ui->textEdit->text());
}

void MainWindow::on_actionSave_As_triggered()
{
    //QString foo = m_helper.getCurrentFileExtension();
    QString filename = QFileDialog::getSaveFileName(this, tr("Save File"), ".", tr("*"));


    std::string str1 = filename.toStdString();

    m_helper.saveFileText(ui->textEdit->text(), filename);
}

void MainWindow::on_actionExit_triggered()
{
    exit(1);
}

void MainWindow::on_actionFont_triggered()
{
    QFont font;
    bool okPressed;
    font = QFontDialog::getFont(&okPressed, this);

    std::string fontname = font.rawName().toStdString();

    if (okPressed)
    {
        QsciLexer* lexer = ui->textEdit->lexer();
        lexer->setFont(font, -1);
        ui->textEdit->setFont(font);
        ui->textEdit->setLexer(lexer);
    }
}

void MainWindow::on_actionSelect_All_triggered()
{
    ui->textEdit->selectAll(true);
}

void MainWindow::on_actionZoom_In_triggered()
{
    ui->textEdit->zoomIn();
}

void MainWindow::on_actionZoom_Out_triggered()
{
    ui->textEdit->zoomOut();
}

void MainWindow::on_actionNew_triggered()
{
    if (m_textChanged)
    {
        // Check for save
    }

    ui->textEdit->clear();
    m_helper.resetCurrentFilename();\
}

void MainWindow::textChanged()
{
    m_textChanged = true;
}
